<template>
  <div class="activity-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="8">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
          添加
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="16">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-date-picker
              v-model="queryForm.activity_range"
              type="daterange"
              value-format="yyyy-MM-dd"
              align="right"
              range-separator="至"
              start-placeholder="项目开始日期"
              end-placeholder="项目结束日期"
              unlink-panels
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.keyword"
              placeholder="搜索项目名称/公司名称/项目经理"
              clearable
              class="search-input"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      @selection-change="setSelectRows"
    >
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="序号"
        width="95"
        type="index"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="activity_name"
        label="项目名称"
        width="120"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="company_name"
        label="公司名称"
        width="220px"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="activity_start"
        label="项目开始日期"
        width="110"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="activity_end"
        label="项目结束日期"
        width="110"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="project_manager"
        label="项目经理"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="name"
        label="创建者"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="is_filed"
        label="是否归档"
      />
      <el-table-column align="center" label="操作" width="240">
        <template #default="{ row }">
          <el-button
            :disabled="row.is_filed == '是'"
            type="text"
            @click="handleExpenses(row)"
          >
            费用管理
          </el-button>
          <el-button
            :disabled="row.is_filed == '是'"
            type="text"
            @click="showChecks(row.id)"
          >
            验收材料
          </el-button>
          <el-button
            type="text"
            :disabled="row.is_del === 2 || row.is_filed == '是'"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            :disabled="row.is_del === 2 || row.is_filed == '是'"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
          <el-button type="text" @click="handleFiled(row)">
            {{ row.is_filed === '是' ? '解档' : '归档' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.page"
      :page-size="queryForm.list_row"
      :layout="layout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <edit ref="edit" @fetch-data="fetchData" />

    <el-dialog
      v-if="checksVisible"
      title="验收材料"
      :visible.sync="checksVisible"
      width="800px"
      top="50px"
    >
      <el-form label-position="top">
        <el-form-item
          v-for="(type, typeIndex) in checkTypes"
          :key="type.id"
          :label="getUploadTypeLabel(type, typeIndex)"
        >
          <div class="checks-row">
            <div
              v-for="(file, fileIndex) in type.fileList"
              :key="file.uid"
              class="check-item"
              :style="{ backgroundImage: `url(${file.url})` }"
            >
              <div class="check-mask">
                <i
                  class="el-icon-delete check-delete" v-if="!type.disabled"
                  @click="removeCheck(typeIndex, fileIndex,type)"
                ></i>
              </div>
            </div>
            <el-upload
              v-if="!type.disabled"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              multiple
              :disabled="type.disabled"
              accept="image/*"
              :limit="6"
              :on-exceed="onChecksExceed"
              :on-change="
                (file, fileList) => onChecksChange(fileList, typeIndex)
              "
              :file-list="type.fileList"
              :show-file-list="false"
            >
              <i class="check-add el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item
          v-if="!checkTypes.length"
          label="该项目无需提交验收材料"
        />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checksVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveChecks">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getList,
    doDelete,
    doFiled,
    getCheckTypes,
    saveChecks,
  } from '@/api/activity'
  import { upload } from '@/api/common'
  import Edit from './components/ActivityEdit'

  export default {
    name: 'Activity',
    components: { Edit },
    data() {
      return {
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          page: 1,
          list_row: 10,
          keyword: '',
          activity_range: null,
          activity_start: '',
          activity_end: '',
        },
        checksVisible: false,
        checkTypes: [],
        currentActivityId: null,
      }
    },
    watch: {
      'queryForm.activity_range'(range) {
        const [start, end] = range || ['', '']
        this.queryForm.activity_start = start
        this.queryForm.activity_end = end
      },
    },
    created() {
      this.fetchData()
    },
    methods: {
      setSelectRows(val) {
        this.selectRows = val
      },
      handleEdit(row) {
        if (row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const msg = await doDelete({ activity_id: row.id })
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              this.$baseMessage(msg, 'success')
              this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleFiled(row) {
        const actionText = row.is_filed === '是' ? '解档' : '归档'
        const isFiledNew = row.is_filed === '是' ? '否' : '是'
        this.$baseConfirm(`你确定要${actionText}当前项吗`, null, async () => {
          const msg = await doFiled({
            activity_id: row.id,
            is_filed: isFiledNew,
          })
          this.$baseMessage(msg, 'success')
          this.fetchData()
        })
      },
      handleExpenses(row) {
        console.log(row)
        const { id: activity_id, activity_name } = row
        this.$router.push({
          name: 'ActivityExpenses',
          query: { activity_id, activity_name },
        })
      },
      handleSizeChange(val) {
        this.queryForm.list_row = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.page = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const { data, total } = await getList(this.queryForm)
        this.list = data
        this.total = total
        this.listLoading = false
      },
      showChecks(id) {
        this.currentActivityId = id
        getCheckTypes({ activity_id: id }).then((res) => {
          const types = res.map((type) => {
            return {
              ...type,
              fileList: type.check_img.map((img) => ({
                uid: Math.random(),
                url: img,
              })),
            }
          })
          // types.unshift({ id: 0, project_category: '未分配', fileList: [] })
          console.log(321,types)
          if(types.length>0){
            types.forEach(item=>{
              this.$set(item,'disabled',false)
              if(item.handler === 2 ){
                item.disabled = true
              }
            })
          }
          console.log(3321,types)
          this.checkTypes = types
          this.checksVisible = true
        })
      },
      handleSaveChecks() {
        if (!this.validateChecks()) return
        const images = []
        const types = this.checkTypes
        types.forEach((type) => {
          const files = type.fileList
          const typeImages = files.map((file) => file.url).join()
          images.push({
            activity_expenses_id: type.id,
            check_img: typeImages,
          })
        })
        const imagesJson = JSON.stringify(images)
        saveChecks({
          activity_id: this.currentActivityId,
          check_img: imagesJson,
        }).then((res) => {
          this.checksVisible = false
          this.$baseMessage(res, 'success')
        })
      },
      onChecksExceed() {
        this.$baseMessage('最多只能上传 6 张图片哦', 'warning')
      },
      onChecksChange(fileList, index) {
        // 注: fileList 包含全部图片
        const type = this.checkTypes[index]
        // 处理待上传图片
        const formData = new FormData()
        fileList
          .filter((file) => file.raw)
          .forEach((file) => formData.append('file[]', file.raw))
        // 上传图片
        upload(formData).then((res) => {
          // 上传后处理
          const urls = res.url
          type.fileList = [
            ...fileList.filter((file) => !file.raw),
            ...urls.map((url) => ({ url })),
          ]
          this.$set(this.checkTypes, index, type)
        })
      },
      getUploadTypeLabel(type, index) {
        let label = type.project_category
        const num = type.fileList.length
        // label += ` ${index ? `(${num}/6)` : num}`
        label += ` (${num}/6)`
        return label
      },
      validateChecks() {
        const types = this.checkTypes
        for (const type of types) {
          const files = type.fileList
          for (const file of files) {
            if (file.url.startsWith('blob:')) {
              this.$baseMessage('图片上传中，请重试', 'error')
              return false
            }
          }
        }
        return true
      },
      removeCheck(typeIndex, fileIndex,file) {
        console.log(432111,typeIndex,fileIndex,file)
        if(file.handler===1){
          this.checkTypes[typeIndex].fileList.splice(fileIndex, 1)
          this.$forceUpdate()
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  .search-input {
    width: 250px;
  }

  .checks-row {
    display: flex;
    align-items: center;
  }

  .check-item {
    position: relative;
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    margin-right: 10px;
    background-position: center;
    background-size: cover;
    border: 1px solid #c0ccda;
    border-radius: 7px;
  }

  .check-mask {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: 0.3s;
  }

  .check-item:hover .check-mask {
    opacity: 1;
  }

  .check-delete {
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 20px;
    color: #fff;
    cursor: pointer;
    transform: translate(-50%, -50%);
  }

  ::v-deep .el-upload--picture-card {
    position: relative;
    width: 100px;
    height: 100px;
  }

  .check-add {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
</style>
